package com.tchcn.cashier.order.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.othershe.nicedialog.BaseNiceDialog;
import com.tchcn.cashier.order.R;
import com.tchcn.cashier.order.activity.MainActivity;
import com.tchcn.cashier.order.adapter.OrderAdapter;
import com.tchcn.cashier.order.dialog.ChooseNumDialog;
import com.tchcn.cashier.order.dialog.ReturnGoodDialog;
import com.tchcn.cashier.order.dialog.SingleTextDialog;
import com.tchcn.library.model.GoodActModel;
import com.tchcn.library.model.TableModel;
import com.tchcn.library.fragment.SDBaseFragment;
import com.tchcn.library.utils.SDNumberUtil;
import com.tchcn.library.utils.SDToast;
import com.tchcn.library.utils.SDViewUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 桌台左侧界面
 * Created by sad on 2018/5/10.
 */

public class OrderLeftFragment extends SDBaseFragment {

    TextView tvTableNum;//桌号
    TextView tvPeopleNum;//就餐人数
    TextView tvTime;//时间
    TextView tvOrderCode;//订单编号
    RecyclerView rvOrder;
    TextView tvRemarks;//备注
    LinearLayout llRemarks;//备注layout
    TextView tvTotalNum;//总数
    TextView tvMoneyTrue;//应付
    TextView tvMoneyMinus;//优惠
    TextView tvMoneyLast;//实付
    TextView tvGuide;//选择桌台开始点餐
    TextView tvClear; //清空
    TextView tvKillOrder;//撤单
    TextView tvSettle;   //结账
    Button btnSettle;//结账
    Button btnConfirm;//下单
    TextView tvReturn;//退菜
    TextView tvHurry;//催菜
    TextView tvAddGood;//加菜
    LinearLayout llOrderBefore;//按钮布局下单前
    LinearLayout llOrderAfter;//按钮布局下单后
    LinearLayout llConfirmedLayout;//已下单商品
    RecyclerView rvConfirmed;//已下单列表
    TextView tvConfirmText;//已下单列表
    MainActivity activity;

    OrderAdapter orderAdapter;
    //已点
    List<GoodActModel> goodLists = new ArrayList<>();

    OrderAdapter comfirmedOrderAdapter;
    List<GoodActModel> goodConfirmedList = new ArrayList<>();
    //是否已下单
    public static boolean isConfirmOrder = false;

    private String remarksId ="";

    private static OrderLeftFragment fragment;

    TableModel tableModel;

    private int totalNumber = 0;//总数量
    private double totalMoney = 0.00;//总价格
    private double freeMoney = 0.00;//优惠金额

    public static OrderLeftFragment getInstance(){
        if(fragment == null){
            fragment = new OrderLeftFragment();
        }
        return fragment;
    }

    public static OrderLeftFragment newInstance() {
        fragment = new OrderLeftFragment();
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.frag_order_left;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        initView(rootView);
        return rootView;
    }

    private void initView(final View v) {
        activity = (MainActivity) getActivity();
        rvOrder = (RecyclerView) v.findViewById(R.id.rv_order);
        rvConfirmed = (RecyclerView) v.findViewById(R.id.rv_order_confirm);
        tvClear = (TextView) v.findViewById(R.id.tv_clear);
        tvKillOrder = (TextView) v.findViewById(R.id.tv_kill_order);
        tvSettle = (TextView) v.findViewById(R.id.tv_settle);
        tvGuide = (TextView) v.findViewById(R.id.tv_guide);
        tvPeopleNum = (TextView) v.findViewById(R.id.tv_people_num);
        tvTableNum = (TextView) v.findViewById(R.id.tv_table_num);
        tvTime = (TextView) v.findViewById(R.id.tv_time);
        tvGuide = (TextView) v.findViewById(R.id.tv_guide);
        tvReturn = (TextView) v.findViewById(R.id.tv_return);
        tvAddGood = (TextView) v.findViewById(R.id.tv_add_good);
        btnSettle = (Button) v.findViewById(R.id.btn_settle);
        tvHurry = (TextView) v.findViewById(R.id.tv_hurry);
        tvRemarks = (TextView) v.findViewById(R.id.tv_remarks);
        tvMoneyLast = (TextView) v.findViewById(R.id.tv_money_last);
        tvMoneyTrue = (TextView) v.findViewById(R.id.tv_money_true);
        tvTotalNum = (TextView) v.findViewById(R.id.tv_total_num);
        llOrderBefore = (LinearLayout) v.findViewById(R.id.ll_order_before);
        llOrderAfter = (LinearLayout) v.findViewById(R.id.ll_order_after);
        llConfirmedLayout = (LinearLayout) v.findViewById(R.id.ll_confirmed_order);
        btnConfirm = (Button) v.findViewById(R.id.btn_confirm);
        tvConfirmText = (TextView) v.findViewById(R.id.tv_confirm_text);
        llRemarks = (LinearLayout) v.findViewById(R.id.ll_remarks);
        btnConfirm.setOnClickListener(this);
        tvAddGood.setOnClickListener(this);
        llRemarks.setOnClickListener(this);
        //清空
        tvClear.setOnClickListener(this);
        //撤单
        tvKillOrder.setOnClickListener(this);
        tvReturn.setOnClickListener(this);


        //结账
        tvSettle.setOnClickListener(this);
        llOrderBefore.setOnClickListener(this);
        tvAddGood.setOnClickListener(this);


        orderAdapter = new OrderAdapter(goodLists);
        orderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(orderAdapter.getSelectNum() == position)
                    orderAdapter.setSelectNum(-1);
                else
                    orderAdapter.setSelectNum(position);
            }
        });
        orderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final GoodActModel actModel = orderAdapter.getData().get(position);
                //点加号操作
                if (view.getId() == R.id.iv_add) {
                    actModel.setCarNum(actModel.getCarNum() + 1);
                    activity.notifyGoodFragment(actModel, true);
                    totalMoney+=actModel.getPrice();
                    totalNumber++;
                } else if (view.getId() == R.id.iv_sub) {  //点减号操作
                    actModel.setCarNum(actModel.getCarNum() - 1);
                    if (actModel.getCarNum() == 0)
                        goodLists.remove(position);
                    activity.notifyGoodFragment(actModel, false);
                    totalMoney-=actModel.getPrice();
                    totalNumber--;
                }
                updateAmountPrice();
                orderAdapter.notifyDataSetChanged();

            }
        });
        orderAdapter.bindToRecyclerView(rvOrder);
        rvOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvOrder.setNestedScrollingEnabled(false);



        comfirmedOrderAdapter = new OrderAdapter(goodConfirmedList);
        comfirmedOrderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                comfirmedOrderAdapter.setSelectNum(position);
            }
        });
        comfirmedOrderAdapter.bindToRecyclerView(rvConfirmed);
        rvConfirmed.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvConfirmed.setNestedScrollingEnabled(false);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
            int i = v.getId();
            if (i == R.id.ll_remarks) {//备注
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
                if (!OrderRemarkFragment.getInstance().isAdded()) {
                    fragmentTransaction.add(R.id.fl_container_right, OrderRemarkFragment.getInstance());
                    fragmentTransaction.commitAllowingStateLoss();
                } else {
                    fragmentTransaction.remove(OrderRemarkFragment.getInstance());
                    fragmentTransaction.commitAllowingStateLoss();
                }
            } else if (i == R.id.tv_clear) {//清空
                goodLists.clear();
                orderAdapter.notifyDataSetChanged();
                orderAdapter.setSelectNum(-1);
                activity.clearGood();
                totalNumber = 0;
                totalMoney =0;
                updateAmountPrice();
            } else if (i == R.id.tv_return) { //退菜
                if(comfirmedOrderAdapter.getNum() == null ){
                    SDToast.showToast("请选择要退的菜品");
                    return;
                }
                if(comfirmedOrderAdapter.getNum().getStatus() ==2){
                    SDToast.showToast("该菜品已退");
                    return;
                }
                final ReturnGoodDialog returnGoodDialog = ReturnGoodDialog.newInstance(comfirmedOrderAdapter.getNum());
                returnGoodDialog.setConvertListener(new ChooseNumDialog.OnDialogClickListener(){
                    @Override
                    public void onItemClick(View view, BaseNiceDialog dialog) {
                        if(view.getId() == R.id.tv_commit){
                            GoodActModel selectGood = comfirmedOrderAdapter.getNum();
                            if(returnGoodDialog.getNum() == selectGood.getCarNum()) {
                                comfirmedOrderAdapter.getNum().setStatus(2);//退菜状态，后续再改
                            }else {
                                comfirmedOrderAdapter.getNum().setCarNum(comfirmedOrderAdapter.getNum().getCarNum() - returnGoodDialog.getNum());
                                GoodActModel goodActModel = new GoodActModel();
                                goodActModel.setId(selectGood.getId());
                                goodActModel.setName(selectGood.getName());
                                goodActModel.setNormsId(selectGood.getNormsId());
                                goodActModel.setSelectNorms(selectGood.getSelectNorms());
                                goodActModel.setPrice(selectGood.getPrice());
                                goodActModel.setCarNum(returnGoodDialog.getNum());
                                goodActModel.setHasNorm(selectGood.getHasNorm());
                                goodActModel.setStatus(2);
                                goodConfirmedList.add(goodActModel);
                            }
                            comfirmedOrderAdapter.notifyDataSetChanged();
                            dialog.dismiss();
                        }
                    }
                })
                        .setWidth(SDViewUtil.px2dp(568))
                        .show(getActivity().getSupportFragmentManager());
            } else if (i == R.id.tv_hurry) {//催菜
            } else if (i == R.id.tv_kill_order) {///撤单
                SingleTextDialog.newInstance(null).setConvertListener(new ChooseNumDialog.OnDialogClickListener() {
                    @Override
                    public void onItemClick(View view, BaseNiceDialog dialog) {
                        if (view.getId() == R.id.tv_commit) {
                            isConfirmOrder = false;
                            goodLists.clear();
                            goodConfirmedList.clear();
                            orderAdapter.notifyDataSetChanged();
                            comfirmedOrderAdapter.notifyDataSetChanged();
                            tvGuide.setVisibility(View.VISIBLE);
                            activity.clearGood();
                            tableModel.setStatus(1);
                            activity.changeRightFragment(ChooseTableFragment.getInstance());
                            dialog.dismiss();
                        }
                    }
                })
                        .setWidth(SDViewUtil.px2dp(568))
                        .show(getActivity().getSupportFragmentManager());
            } else if (i == R.id.tv_add_good) {//加菜
                isConfirmOrder = false;
                tvConfirmText.setVisibility(View.VISIBLE);
                tvClear.setVisibility(View.VISIBLE);
                tvReturn.setVisibility(View.GONE);
                tvHurry.setVisibility(View.GONE );
                llOrderBefore.setVisibility(View.VISIBLE);
                llOrderAfter.setVisibility(View.GONE);
                activity.changeRightFragment(ChooseGoodFragment.getInstance());
            } else if (i == R.id.btn_settle || i == R.id.tv_settle) {//结账
            } else if (i == R.id.btn_confirm) {//下单
                isConfirmOrder = true;
                tvClear.setVisibility(View.GONE);
                tvReturn.setVisibility(View.VISIBLE);
                tvHurry.setVisibility(View.VISIBLE );
                llOrderBefore.setVisibility(View.GONE);
                llOrderAfter.setVisibility(View.VISIBLE);
                llConfirmedLayout.setVisibility(View.VISIBLE);
                tvConfirmText.setVisibility(View.GONE);
                //菜品状态已下单
                for (int j = 0; j < goodLists.size(); j++) {
                    goodLists.get(j).setStatus(1);
                    goodConfirmedList.add(goodLists.get(j));
                }
                //清空购物车
                goodLists.clear();
                orderAdapter.notifyDataSetChanged();
                comfirmedOrderAdapter.notifyDataSetChanged();
                //修改餐桌状态
                tableModel.setStatus(3);//开台
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
                tableModel.setDay(sdf.format(date));
                sdf = new SimpleDateFormat("HH:mm");
                tableModel.setTime(sdf.format(date));
                activity.changeRightFragment(ChooseTableFragment.getInstance());
            }
    }



    public void addShopCart(GoodActModel goodActModel) {
        if(!isConfirmOrder) {
            tvGuide.setVisibility(View.GONE);
            boolean hasGood = false;
            for (int i = 0; i < goodLists.size(); i++) {
                GoodActModel good = goodLists.get(i);
                if (goodActModel.getId() == good.getId()) {
                    if (goodActModel.getHasNorm() == 1) {
                        if (goodActModel.getNormsId().equals(good.getNormsId())) {
                            hasGood = true;
                            good.setCarNum(good.getCarNum() + 1);
                        }
                    } else {
                        hasGood = true;
                        good.setCarNum(good.getCarNum() + 1);
                    }
                }
            }
            if (!hasGood) {
                GoodActModel actModel = new GoodActModel();
                actModel.setId(goodActModel.getId());
                actModel.setName(goodActModel.getName());
                actModel.setNormsId(goodActModel.getNormsId());
                actModel.setSelectNorms(goodActModel.getSelectNorms());
                actModel.setPrice(goodActModel.getPrice());
                actModel.setCarNum(1);
                actModel.setHasNorm(goodActModel.getHasNorm());
                goodLists.add(actModel);
            }
            totalNumber++;
            totalMoney += goodActModel.getPrice();
            updateAmountPrice();
            orderAdapter.notifyDataSetChanged();
        }
    }

    public void setTableData(TableModel tableModelData) {
        tableModel = tableModelData;
        tvPeopleNum.setText("人数："+ tableModelData.getNum());
        tvTableNum.setText("桌号："+ tableModelData.getTableid());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        tvTime.setText(dateFormat.format(new Date()));
    }

    public void setRemarks(String remarks,String remarksId){
        this.remarksId = remarksId;
        tvRemarks.setText(remarks);
        FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
        fragmentTransaction.remove(OrderRemarkFragment.getInstance());
        fragmentTransaction.commitAllowingStateLoss();
    }


    private void updateAmountPrice(){
       tvMoneyLast.setText("￥" + SDNumberUtil.doubleTrans(totalMoney));
       tvMoneyTrue.setText("￥" + SDNumberUtil.doubleTrans(totalMoney));
        tvTotalNum.setText("总计:" + totalNumber);
        for (int i = 0; i < goodLists.size(); i++) {

        }
    }


}
